/**
 * TemplateMsgFactoryImpl.java<br>
 *
 *
 * @version 下午6:56:37
 */
package com.iwechat.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iwechat.emuns.ConstEmus;
import com.iwechat.mybatis.generator.dao.TmpsTemplateConfigMapper;
import com.iwechat.mybatis.generator.model.TmpsTemplateConfig;
import com.iwechat.service.MsgTemplateFactory;
import com.iwechat.service.RefreshAble;
import com.iwechat.util.DataUtil;

/**
 * 消息模板工厂<br>
 * 获取并解析模板文件，已经将数据库中对应的值进行替换
 *
 *
 */
@Service("msgtmfc")
public class MsgTemplateFactoryImpl implements MsgTemplateFactory, RefreshAble {
    private static final Logger            logger     = LogManager.getLogger();
    private static final String            FILE_STORE = "json";

    @Autowired
    TmpsTemplateConfigMapper               mapper;

    private volatile Map<Integer, String>  dataMap;
    private volatile Map<Integer, Integer> levelMap;

    @Override
    public void refresh() {
        Map<Integer, String> dataMap = new HashMap<Integer, String>();
        Map<Integer, Integer> levelMap = new HashMap<Integer, Integer>();
        Map<String, String> jsonFileMap = new HashMap<String, String>();
        String path = DataUtil.getConfigPath(FILE_STORE);
        File dir = new File(path);
        if (dir.exists()) {
            BufferedReader reader = null;
            InputStreamReader isr = null;
            FileInputStream fis = null;
            StringBuffer buffer = null;
            String line;
            String value;
            try {
                // 1. 解析文件
                for (File f : dir.listFiles()) {
                    String fileName = f.getName();
                    // 只解析json结尾的文件
                    if (fileName.endsWith(".json")) {
                        String fileId = fileName.substring(0, fileName.lastIndexOf("."));
                        fis = new FileInputStream(f);
                        isr = new InputStreamReader(fis, "UTF-8");
                        reader = new BufferedReader(isr);
                        buffer = new StringBuffer((int) f.length());
                        while ((line = reader.readLine()) != null) {
                            buffer.append(line.trim());
                        }
                        value = buffer.toString();
                        jsonFileMap.put(fileId, value);
                        // 关闭流
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (Exception e) {
                            }
                        }
                        if (isr != null) {
                            try {
                                isr.close();
                            } catch (Exception e) {
                            }
                        }
                        if (reader != null) {
                            try {
                                reader.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
                // 2. 根据数据库查询的数据初始化模板,一条数据库记录一个模板
                List<TmpsTemplateConfig> tempDbList = mapper.queryAll();
                for (TmpsTemplateConfig c : tempDbList) {
                    int key = c.getTemplateId();
                    String tempFileId = c.getJsonFile();
                    String val = jsonFileMap.get(tempFileId);
                    // 替换参数
                    val = val.replace(ConstEmus.$templateid.value(), c.getWxTemplateId());
                    val = val.replace(ConstEmus.$linkurl.value(), c.getLinkUrl());
                    val = val.replace(ConstEmus.$generalField.value(), c.getGeneralField());
                    val = val.replace(ConstEmus.$color.value(), c.getColor());
                    // 设置到dataMap中
                    dataMap.put(key, val);
                    levelMap.put(key, c.getPriority());

                }

            } catch (Exception e) {
                logger.error(e, e);
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (Exception e) {
                    }
                }
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (Exception e) {
                    }
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                }
            }

        } else {
            logger.error("config path: " + path + "not exists!");
        }

        synchronized (this) {
            this.dataMap = dataMap;
            this.levelMap = levelMap;
        }

        logger.info("### " + this + " refresh succeed!");

    }

    /*
     * (non-Javadoc)
     *
     * @see com.iwechat.service.TemplateMsgFactory#getTemplateJson(java.lang.String)
     */
    @Override
    public String getTemplate(int templateId) {
        return dataMap.get(templateId);
    }

    @PostConstruct
    public void init() {
        logger.info("### " + this + " init succeed!");
    }

    @Override
    public int getPriority(int templateId) {
        return this.levelMap.get(templateId);
    }

}
